<?php

namespace system\core;

/**
 * Each instance of Route holds routing information 
 * such as url pattern and entry point Component, also has
 * all necessary methods for match givin URL to to concrete 
 * pattern.
 *
 * @package system\core
 * @author Pavel Egorov {@link mailto:pavel@egorov.ru pavel@egorov.ru}
 * @version 0.0.1 $Revision$
 * @copyright Copyright (c) 2011, Pavel Egorov
 */
final class Route {

    private $route;
    private $pattern;
    private $entryPointComponent;

    /**
     * Creates instance of Route
     *
     * @param String $route - pattern for this route
     * @param String $entryPointComponent - entry point {@link DocumentComponent} name
     */
    public function __construct($route, $entryPointComponent) {
        $this->route = $route;
        $this->entryPointComponent = $entryPointComponent;
        $this->pattern = $this->route;
        while (preg_match('#\:(.[a-z_0-9]*)\((.*)\)#', $this->pattern)) {
            $this->pattern = preg_replace('#\:(.[a-z_0-9]*)\((.*)\)#', '($2)', $this->pattern);
        }
        $this->pattern = str_replace('|', '/?', $this->pattern);
    }

    /**
     * Match $queryString to this URL pattern.
     *
     * @param String $queryString
     * @return bool TRUE if matched FALSE otherwise
     */
    public function matchRoute($queryString) {
        if (preg_match('#^' . $this->pattern . '$#', $queryString)) {
            return true;
        }
        return false;
    }

    /**
     * Extracts variable names and values from auery string and set them into $_GET array
     *
     * @param String $queryString
     */
    public function setGETvars($queryString) {
        preg_match_all('#:(.[a-z_0-9]+)#', $this->route, $var);
        preg_match('#^' . $this->pattern . '$#', $queryString, $vals);
        for ($i = 0, $k = 1; $i < sizeof($var[1]); ++$i, ++$k) {
            $_GET[$var[1][$i]] = $vals[$k];
        }
    }

    /**
     * Returns route for this {@link Route}
     * 
     * @return String route pattern for this {@link Route}
     */
    public function getRoute() {
        return $this->route;
    }

    /**
     * Returns entry point {@link DocumentComponent}  for this {@link Route}
     *
     * @return String entry point for this {@link Route}
     */
    public function getEntryPoint() {
        return $this->entryPointComponent;
    }

}